package cc.shacocloud.mirage.restful;

import cc.shacocloud.mirage.restful.bind.annotation.HttpMethod;
import cc.shacocloud.mirage.restful.bind.annotation.PathPatterns;
import cc.shacocloud.mirage.utils.resource.ResourceUtil;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

/**
 * 静态资源处理器注册程序
 *
 * @author 思追(shaco)
 */
public class StaticResourceHandlerRegistry {
    
    @Getter
    private final Map<RequestMappingInfo, StaticResourceHandler> staticResourceHandlerMap = new HashMap<>();
    
    /**
     * 添加静态资源处理器
     * <p>
     * 前缀路径匹配，示例：/static/* 以 /static/ 开头的路径的请求都将从目录 {@link StaticResourceHandler#DEFAULT_WEB_ROOT} 得到响应，
     * 例如，如果请求路径为 static/css/styles.css，则静态服务将在目录 webroot/css/styles.css 中查找文件，
     * 也可以通过 {@link #addRootHandler(String, String...)} 自定义根路径
     *
     * @param paths 路由路径
     * @return {@link StaticResourceHandler}
     */
    public StaticResourceHandler addHandler(String... paths) {
        RequestMappingInfo mappingInfo = RequestMappingInfo.builder()
                .pathPatterns(PathPatterns.PATH)
                .methods(new HttpMethod[]{HttpMethod.GET})
                .paths(paths)
                .build();
        return addHandler(mappingInfo);
    }
    
    /**
     * 添加静态资源处理器
     *
     * @param paths   路由路径
     * @param webRoot 相对于 {@code pathPattern} 的路径前缀，支持 {@link ResourceUtil#CLASSPATH_URL_PREFIX} 和 {@link ResourceUtil#FILE_URL_PREFIX} 协议
     * @return {@link StaticResourceHandler}
     */
    public StaticResourceHandler addRootHandler(String webRoot, String... paths) {
        RequestMappingInfo mappingInfo = RequestMappingInfo.builder()
                .pathPatterns(PathPatterns.PATH)
                .methods(new HttpMethod[]{HttpMethod.GET})
                .paths(paths)
                .build();
        return addHandler(mappingInfo, webRoot);
    }
    
    
    /**
     * 添加静态资源处理器
     *
     * @param requestMappingInfo 请求映射信息
     * @return {@link StaticResourceHandler}
     */
    public StaticResourceHandler addHandler(RequestMappingInfo requestMappingInfo) {
        StaticResourceHandler staticResourceHandler = new StaticResourceHandlerImpl();
        this.staticResourceHandlerMap.put(requestMappingInfo, staticResourceHandler);
        return staticResourceHandler;
    }
    
    /**
     * 添加静态资源处理器
     *
     * @param requestMappingInfo 请求映射信息
     * @param webRoot            相对于 {@code pathPattern} 的路径前缀，支持 {@link ResourceUtil#CLASSPATH_URL_PREFIX} 和 {@link ResourceUtil#FILE_URL_PREFIX} 协议
     * @return {@link StaticResourceHandler}
     */
    public StaticResourceHandler addHandler(RequestMappingInfo requestMappingInfo,
                                            String webRoot) {
        StaticResourceHandler staticResourceHandler = new StaticResourceHandlerImpl(webRoot);
        this.staticResourceHandlerMap.put(requestMappingInfo, staticResourceHandler);
        return staticResourceHandler;
    }
    
}
